home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4332 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.1 KB  |  69 lines

  1. Path: axl.dialup.fu-berlin.DE!not-for-mail
  2. From: axl@zedat.fu-berlin.de (Axel Thimm)
  3. Newsgroups: comp.lang.c,comp.lang.c++,gnu.gcc.help,gnu.g++.help,comp.os.msdos.djgpp
  4. Subject: float != float and floats as return types
  5. Date: Mon, 29 Jan 1996 20:12:38 GMT
  6. Organization: FU Berlin
  7. Message-ID: <4ej9lb$mpc@fu-berlin.de>
  8. Reply-To: axl@zedat.fu-berlin.de
  9. NNTP-Posting-Host: axl.dialup.fu-berlin.de (160.45.218.93)
  10. X-Access: 16 17 19
  11. X-Newsreader: Forte Free Agent 1.0.82
  12.  
  13. Hello,
  14. I am getting confused, about how C/C++ manage float binary operations,
  15. in particular multiplication. The next C++ example gives me surprising
  16. results:
  17.     *** cut here: begin file t_prec.cc
  18.     #include <iostream.h>
  19.     #include <iomanip.h>
  20.     #include <math.h>
  21.     float quad( float );
  22.     int main() {
  23.       for( int i=0; i<10; ++i ) {
  24.         float a, b, c;
  25.         a = i/13.123123;
  26.         b = a*a;
  27.         c = quad(a);
  28.         cout << (b - c) << '\t';
  29.         cout << (b - a*a) << '\t';
  30.         cout << (c - quad(a)) << '\n';
  31.       }
  32.       return 0;
  33.     }
  34.     float quad( float x ) { return x*x; }
  35.     *** cut here: end file t_prec.cc
  36. (Sorry for not using C-syntax. You can substitute the "cout <<" part
  37. with "printf" calls, I realized it to late to try it out, and
  38. "translating" it on the fly might get typos in)
  39. I compile with the MSDOS port of gcc as follows: gcc t_prec.cc -lgpp 
  40. So here is my output:
  41.     *** cut here: begin output
  42.     0    0    0
  43.     0    3.21547e-11    3.21547e-11
  44.     0    1.28619e-10    1.28619e-10
  45.     0    -1.25443e-09    -1.25443e-09
  46.     0    5.14475e-10    5.14475e-10
  47.     0    7.14357e-10    7.14357e-10
  48.     0    -5.01772e-09    -5.01772e-09
  49.     0    -1.46904e-08    -1.46904e-08
  50.     0    2.0579e-09    2.0579e-09
  51.     0    -2.02694e-09    -2.02694e-09
  52.     *** cut here: end output
  53. At first I thought all numbers should be zeros. The middle column might
  54. not be zero, if the compiler calculates in higher precision than what
  55. the variables are, so an intermediate storage (b) might loose some
  56. digits, but I cannot understand what happens with c! Both times a
  57. function is called, that _is_not_ inlined, so in both cases the same
  58. loss of digits should be observed.
  59. Any ideas?
  60.  
  61. Regards
  62.     Axel Thimm
  63.  
  64. ===
  65. Axel Thimm <axl@zedat.fu-berlin.de>
  66. Freie Universitaet Berlin
  67. ===
  68.  
  69.